package Zoomanagement;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

// Main Class - Provides GUI for zoo management
public class ZooManagementSystem {
    private ZooAPI southernZone;
    private ZooAPI northernZone;
    private JTextArea displayArea;
    private JPanel mainPanel;

    public ZooManagementSystem() {
        // Create two zoo instances
        southernZone = new Zoo("Southern-Zone Zoo");
        northernZone = new Zoo("Northern-Zone Zoo");

        // Add 5 animals to Southern-Zone Zoo
        southernZone.addAnimal(new Animal("Simba", "African Lion", 6));
        southernZone.addAnimal(new Animal("Dumbo", "African Elephant", 12));
        southernZone.addAnimal(new Animal("Luna", "Gray Wolf", 4));
        southernZone.addAnimal(new Animal("Poe", "Raven", 3));
        southernZone.addAnimal(new Animal("Benny", "Grizzly Bear", 8));

        // Add 5 animals to Northern-Zone Zoo
        northernZone.addAnimal(new Animal("Arctic", "Polar Bear", 7));
        northernZone.addAnimal(new Animal("Blizzard", "Snow Leopard", 5));
        northernZone.addAnimal(new Animal("Frost", "Arctic Fox", 3));
        northernZone.addAnimal(new Animal("Penguin", "Emperor Penguin", 4));
        northernZone.addAnimal(new Animal("Aurora", "Caribou", 6));

        // Initialize GUI
        initializeMainPanel();
    }

    private void initializeMainPanel() {
        mainPanel = new JPanel(new BorderLayout());

        // Create a text area to display information
        displayArea = new JTextArea();
        displayArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(displayArea);
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // Create a panel for buttons
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(7, 1));

        // Create buttons
        JButton displaySouthern = new JButton("Display all animals in Southern-Zone Zoo");
        JButton displayNorthern = new JButton("Display all animals in Northern-Zone Zoo");
        JButton moveAnimal = new JButton("Move an animal between zoos");
        JButton addAnimal = new JButton("Add a new animal to a zoo");
        JButton removeAnimal = new JButton("Remove an animal from a zoo");
        JButton findAnimal = new JButton("Find an animal");
        JButton exitButton = new JButton("Exit");

        // Add buttons to the panel
        buttonPanel.add(displaySouthern);
        buttonPanel.add(displayNorthern);
        buttonPanel.add(moveAnimal);
        buttonPanel.add(addAnimal);
        buttonPanel.add(removeAnimal);
        buttonPanel.add(findAnimal);
        buttonPanel.add(exitButton);

        // Add the button panel to the main panel
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        // Add action listeners to buttons
        displaySouthern.addActionListener(e -> displayAnimals(southernZone));
        displayNorthern.addActionListener(e -> displayAnimals(northernZone));
        moveAnimal.addActionListener(e -> moveAnimalBetweenZoos());
        addAnimal.addActionListener(e -> addNewAnimal());
        removeAnimal.addActionListener(e -> removeAnimalFromZoo());
        findAnimal.addActionListener(e -> findAnimalInZoos());
        exitButton.addActionListener(e -> System.exit(0));
    }

    private void displayAnimals(ZooAPI zoo) {
        displayArea.setText("");
        StringBuilder sb = new StringBuilder();
        sb.append("\n=== ").append(zoo.getName()).append(" Animals ===\n");
        for (int i = 0; i < zoo.getCounter(); i++) {
            Animal animal = zoo.getAnimal(i);
            sb.append("Name: ").append(animal.getName()).append(" | Species: ").append(animal.getSpecies()).append(" | Age: ").append(animal.getAge()).append("\n");
        }
        displayArea.setText(sb.toString());
    }

    private void moveAnimalBetweenZoos() {
        String[] options = {"Move from Southern-Zone to Northern-Zone", "Move from Northern-Zone to Southern-Zone"};
        int moveChoice = JOptionPane.showOptionDialog(mainPanel, "Choose a direction to move the animal:", "Move Animal",
                JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

        ZooAPI from = (moveChoice == 0) ? southernZone : northernZone;
        ZooAPI to = (moveChoice == 0) ? northernZone : southernZone;

        StringBuilder sb = new StringBuilder();
        sb.append("Available animals in ").append(from.getName()).append(":\n");
        for (int i = 0; i < from.getCounter(); i++) {
            Animal animal = from.getAnimal(i);
            sb.append("Name: ").append(animal.getName()).append(" | Species: ").append(animal.getSpecies()).append(" | Age: ").append(animal.getAge()).append("\n");
        }
        displayArea.setText(sb.toString());

        if (from.getCounter() == 0) {
            JOptionPane.showMessageDialog(mainPanel, "No animals available to move.");
            return;
        }

        String animalName = JOptionPane.showInputDialog(mainPanel, "Enter the name of the animal to move:");
        int index = from.findAnimal(animalName);
        if (index != -1) {
            JOptionPane.showMessageDialog(mainPanel, "Setting up logistics for the move...");

            double vehicleCost;
            try {
                vehicleCost = Double.parseDouble(JOptionPane.showInputDialog(mainPanel, "Enter vehicle cost: RMB"));
                if (vehicleCost < 0) throw new IllegalArgumentException("Vehicle cost cannot be negative.");
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(mainPanel, "Invalid vehicle cost.");
                return;
            }

            double fuelCost;
            try {
                fuelCost = Double.parseDouble(JOptionPane.showInputDialog(mainPanel, "Enter fuel cost: RMB"));
                if (fuelCost < 0) throw new IllegalArgumentException("Fuel cost cannot be negative.");
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(mainPanel, "Invalid fuel cost.");
                return;
            }

            int numCaretakers;
            do {
                try {
                    numCaretakers = Integer.parseInt(JOptionPane.showInputDialog(mainPanel, "Enter the number of caretakers (between 1 and 3):"));
                    if (numCaretakers < 1 || numCaretakers > 3) {
                        JOptionPane.showMessageDialog(mainPanel, "Invalid input! Please enter a number between 1 and 3.");
                    }
                } catch (NumberFormatException ex) {
                    numCaretakers = 0;
                    JOptionPane.showMessageDialog(mainPanel, "Invalid input! Please enter a valid number.");
                }
            } while (numCaretakers < 1 || numCaretakers > 3);

            String[] caretakers = new String[numCaretakers];
            for (int i = 0; i < numCaretakers; i++) {
                caretakers[i] = JOptionPane.showInputDialog(mainPanel, "Enter name of caretaker " + (i + 1) + ":");
                if (caretakers[i] == null || caretakers[i].trim().isEmpty()) {
                    JOptionPane.showMessageDialog(mainPanel, "Caretaker name cannot be empty.");
                    return;
                }
            }

            Item vehicle = new Item("Transport Truck", "VEH_001");
            vehicle.setPrice(vehicleCost);
            Item fuel = new Item("Diesel Fuel", "FUEL_001");
            fuel.setPrice(fuelCost);
            Logistics logistics = new Logistics(vehicle, fuel, caretakers);
            from.moveAnimal(animalName, (Zoo) to, logistics);

            displayAnimals(southernZone);
            displayAnimals(northernZone);
        } else {
            JOptionPane.showMessageDialog(mainPanel, "--- Animal '" + animalName + "' not found in " + from.getName());
        }
    }

    private void addNewAnimal() {
        String[] options = {"Add to Southern-Zone Zoo", "Add to Northern-Zone Zoo"};
        int addChoice = JOptionPane.showOptionDialog(mainPanel, "Choose a zoo to add the animal:", "Add Animal",
                JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

        ZooAPI selectedZooForAdd = (addChoice == 0) ? southernZone : northernZone;

        String name = JOptionPane.showInputDialog(mainPanel, "Enter animal name:");
        if (name == null || name.trim().isEmpty()) {
            JOptionPane.showMessageDialog(mainPanel, "Animal name cannot be empty.");
            return;
        }

        String species = JOptionPane.showInputDialog(mainPanel, "Enter animal species:");
        if (species == null || species.trim().isEmpty()) {
            JOptionPane.showMessageDialog(mainPanel, "Animal species cannot be empty.");
            return;
        }

        int age;
        try {
            age = Integer.parseInt(JOptionPane.showInputDialog(mainPanel, "Enter animal age:"));
            if (age < 0) {
                JOptionPane.showMessageDialog(mainPanel, "Animal age cannot be negative.");
                return;
            }
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(mainPanel, "Invalid age! Please enter a valid number.");
            return;
        }

        Animal newAnimal = new Animal(name, species, age);
        selectedZooForAdd.addAnimal(newAnimal);

        displayAnimals(selectedZooForAdd);
    }

    private void removeAnimalFromZoo() {
        String[] options = {"Remove from Southern-Zone Zoo", "Remove from Northern-Zone Zoo"};
        int removeChoice = JOptionPane.showOptionDialog(mainPanel, "Choose a zoo to remove the animal from:", "Remove Animal",
                JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

        ZooAPI selectedZooForRemove = (removeChoice == 0) ? southernZone : northernZone;

        StringBuilder sb = new StringBuilder();
        sb.append("Available animals in ").append(selectedZooForRemove.getName()).append(":\n");
        for (int i = 0; i < selectedZooForRemove.getCounter(); i++) {
            Animal animal = selectedZooForRemove.getAnimal(i);
            sb.append("Name: ").append(animal.getName()).append(" | Species: ").append(animal.getSpecies()).append(" | Age: ").append(animal.getAge()).append("\n");
        }
        displayArea.setText(sb.toString());

        if (selectedZooForRemove.getCounter() == 0) {
            JOptionPane.showMessageDialog(mainPanel, "No animals to remove.");
            return;
        }

        String animalToRemove = JOptionPane.showInputDialog(mainPanel, "Enter the name of the animal to remove:");
        if (animalToRemove == null || animalToRemove.trim().isEmpty()) {
            JOptionPane.showMessageDialog(mainPanel, "Animal name cannot be empty.");
            return;
        }
        selectedZooForRemove.deleteAnimal(animalToRemove);
        displayAnimals(selectedZooForRemove);
    }

    private void findAnimalInZoos() {
        String animalToFind = JOptionPane.showInputDialog(mainPanel, "Enter the name of the animal to find:");
        if (animalToFind == null || animalToFind.trim().isEmpty()) {
            JOptionPane.showMessageDialog(mainPanel, "Animal name cannot be empty.");
            return;
        }

        int indexSouthern = southernZone.findAnimal(animalToFind);
        int indexNorthern = northernZone.findAnimal(animalToFind);

        if (indexSouthern != -1) {
            Animal animal = southernZone.getAnimal(indexSouthern);
            displayArea.setText("Animal found in Southern-Zone Zoo:\n" +
                    "Name: " + animal.getName() + " | Species: " + animal.getSpecies() + " | Age: " + animal.getAge() + "\n");
        } else if (indexNorthern != -1) {
            Animal animal = northernZone.getAnimal(indexNorthern);
            displayArea.setText("Animal found in Northern-Zone Zoo:\n" +
                    "Name: " + animal.getName() + " | Species: " + animal.getSpecies() + " | Age: " + animal.getAge() + "\n");
        } else {
            displayArea.setText("Animal '" + animalToFind + "' not found in either zoo.");
        }
    }

    public JPanel createMainPanel() {
        return mainPanel;
    }

    public JPanel getMainPanel() {
        return mainPanel;
    }
}